<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon"/>
    <title>Audio Network - https://slides.com/robertrypula - simple AudioContext graph microphone</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">

    <script>
      var audioContext, microphoneNode, gainNode;

      function init() {
        audioContext = new AudioContext();
        gainNode = audioContext.createGain();

        connectMicrophoneTo(gainNode);
        gainNode.connect(audioContext.destination);

        onVolumeChange(gainNode.gain.value);
      }

      function connectMicrophoneTo(audioNode) {
        var
          self = this,
          constraints = {
            video: false,
            audio: true
          };

        navigator.mediaDevices.getUserMedia(constraints)
          .then(function (stream) {
            microphoneNode = audioContext.createMediaStreamSource(stream);
            microphoneNode.connect(audioNode);
          })
          .catch(function (error) {
            alert(error);
          });
      }

      function onVolumeChange(volume) {
        var currentTime = audioContext.currentTime;

        gainNode.gain.setValueAtTime(volume, currentTime)
        document.getElementById('volume').innerHTML = (100 * volume).toFixed(0);
      }
    </script>
</head>
<body>
  <div>
    <button type="button" onClick="init()">Init</button>
  </div>
  <div>
    Microphone volume:
    <input type="range" min="0" max="1" value="1" step="0.01" onChange="onVolumeChange(this.value)" />
    <span id="volume"></span>%
  </div>
</body>
</html>